package cn.stylefeng.guns.sys.core.redis;


import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * Redis key过期监听器, 过期后期的key是无法获取到对应值的
 *
 * @author zhushengjie
 * @date 2022-09-09
 * @see KeyExpirationEventMessageListener#onMessage(Message, byte[])
 */
public abstract class AbstractRedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public AbstractRedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expKey = message.toString();
        String prefix = needHandleExpKeyPrefix();
        if (StrUtil.startWith(expKey, prefix, true)) {
            this.handleMessage(expKey);
        }
    }


    /**
     * 需要处理的过期key的前缀, 不是此前缀的暂时不做处理
     *
     * @return 前缀
     */
    abstract String needHandleExpKeyPrefix();


    /**
     * 处理过期key
     *
     * @param expKey 过期key
     */
    abstract void handleMessage(String expKey);
}
